package xyz.gzdxc.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class UploadUtil {
    private static final Logger LOG = LoggerFactory.getLogger(UploadUtil.class);

    /**
     * upload a file list to a path
     *
     * @param path  the path to upload to
     * @param fileList the file list to upload
     * @return the file list which uploaded
     */
    public static List<File> upload(String path, List<MultipartFile> fileList){
        List<File> resultList = new ArrayList<File>();
        for(MultipartFile multipartFile : fileList){
            String fileName = multipartFile.getResource().getFilename();
            LOG.info("begin to upload the file => {}", fileName);
            File save = new File(path, fileName);
            LOG.info("upload to the path => {}", save.getPath());
            try {
                multipartFile.transferTo(save);
                LOG.info("file upload success => {}", fileName);
                resultList.add(save);
            } catch (IOException e) {
                e.printStackTrace();
                LOG.error(e.toString());
                LOG.error("file upload fail => {}", fileName);
            }
        }
        return resultList;
    }

    /**
     * download a file to the browser
     * @param response the HttpServletResponse
     * @param filePath the path of the file which to download
     * @return void
     */
    public static void download(HttpServletResponse response, String filePath){
        LOG.info("the path of the download file => {}", filePath);
        OutputStream out = null;
        InputStream in = null;
        try {
            File file = new File(filePath);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            out = response.getOutputStream();
            in = new FileInputStream(filePath);
            StreamUtils.copy(in, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            LOG.info(e.toString());
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    LOG.info(e.toString());
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (IOException e){
                    e.printStackTrace();
                    LOG.info(e.toString());
                }
            }
        }
    }
}
